﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using IceTea.Domain;

namespace IceTea.Security
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited=true, AllowMultiple=false)]
    public class IceTeaAuthorizeAttribute : AuthorizeAttribute
    {
        private readonly SecurityRole _roles;

        public IceTeaAuthorizeAttribute(SecurityRole securityRoles)
        {
            _roles = securityRoles;
        }

        public IceTeaAuthorizeAttribute()
        {
            _roles = SecurityRole.ValidUser;
        }

        internal bool PerformAuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            return this.AuthorizeCore(httpContext);
        }

        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            bool result = base.AuthorizeCore(httpContext);
            if (result == true)
            {
                IceTeaPrincipal principal = httpContext.User as IceTeaPrincipal;
                if (principal != null)
                {
                    result = principal.IsInRole(_roles);
                }
            }

            return result;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //If the authorization failed, should render the _Unauthorized view
            filterContext.Result = new ViewResult()
            {
                 ViewName = "_Unauthorized",
                 ViewData = new ViewDataDictionary()
            };
            //base.HandleUnauthorizedRequest(filterContext);
        }
    }
}
